#include "TM1637_Display.h"
#include <stdio.h>
#include <string.h>

void TM1637::start()
{
    CLK.write(1);
    DIO.write(1);

    delay_us(delay_time);

    DIO.write(0);
    delay_us(delay_time);
    CLK.write(0);
    delay_us(delay_time);
}

void TM1637::stop()
{
    CLK.write(0);
    delay_us(delay_time);
    DIO.write(0);

    delay_us(delay_time);

    CLK.write(1);
    delay_us(delay_time);
    DIO.write(1);
    delay_us(delay_time);
}

void TM1637::send_8b(uint8_t byte)
{

    for (int i = 0; i < 8; i++)
    {
        CLK.write(0);
        delay_us(delay_time);
        if ((byte >> i) & 0x01)
        {
            DIO.write(1);
        }
        else
        {
            DIO.write(0);
        }

        delay_us(delay_time);
        CLK.write(1);
        delay_us(delay_time);
    }
    CLK.write(0);
    delay_us(delay_time);
    DIO.write(1);
    delay_us(delay_time);
    CLK.write(1);
    delay_us(delay_time);
    while (DIO.read() == 1)
        ;
}

void TM1637::send_cmd(uint8_t cmd)
{
    start();
    send_8b(cmd);
    stop();
}

void TM1637::send_data(uint8_t addr, uint8_t data)
{
    start();
    send_8b(addr);
    send_8b(data);
    stop();
}

uint8_t SEGData[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
void TM1637::test()
{
    send_cmd(0x44);
    send_data(0xc0, 0x3f);
    send_data(0xc1, 0x3f);
    send_data(0xc2, 0x3f);
    send_data(0xc3, 0x3f);
    send_cmd(0x8a);
}

void TM1637::show_num(int data)
{
    data = data > 9999 ? 9999 : data;
    data = data < -999 ? -999 : data;
    char buf[10];
    sprintf(buf, "%d", data);
    int len = strlen(buf);

    /*for (int i = 0; i < len; i++)
    {
        uint8_t show_data = SEGData[buf[len - 1 - i] - '0'];
        if (buf[len - 1 - i] <'0'||)
            show_data = 0x80;
        send_data(0xc3 - i, show_data);
    }*/
    send_data(0xc0, 0x00);
    send_data(0xc1, 0x00);
    send_data(0xc2, 0x00);
    send_data(0xc3, 0x00);
    int count = 0;
    for (int i = len - 1; i >= 0; i--)
    {
        uint8_t show_data = SEGData[buf[i] - '0'];
        if (buf[i] == '-')
            show_data = 0x40;
        send_data(0xc3 - (count++), show_data);
    }
}
